package com.duolaibei.business.view.fragment;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duolaibei.business.R;
import com.duolaibei.business.api.ApiName;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.base.BaseFragment;
import com.duolaibei.business.config.DIR;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.http.HttpUtils;
import com.duolaibei.business.model.ResponseResult;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.GsonUtil;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.SysUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.utils.log.LogDebug;
import com.duolaibei.business.view.App;
import com.duolaibei.business.view.activity.BlueToothStateActivity;
import com.duolaibei.business.view.activity.LoginModeActivity;
import com.duolaibei.business.view.activity.OutTimeSetActivity;
import com.duolaibei.business.view.dialog.TipDialog;
import com.duolaibei.business.widget.ToggleButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * Created by xlm on 2017/10/30 0030
 * 设置信息
 */

public class SetupFragment extends BaseFragment {

    @Inject(R.id.back)
    private RelativeLayout mLayoutBack;
    @Inject(R.id.title)
    private TextView mTextViewTitle;
    @Inject(R.id.bluetooth_print)
    private RelativeLayout mLayoutBluePrint;
    @Inject(R.id.setup_check_newversion)
    private RelativeLayout mLayoutCheckVersion;
    @Inject(R.id.setup_outtime)
    private RelativeLayout mLayoutOuttime;
    @Inject(R.id.exit_app)
    private RelativeLayout mLayoutExit;
    @Inject(R.id.toogle_button)
    private ToggleButton mToggleButton;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.fragment_setup);
    }

    @Override
    protected void initViews() {
        mLayoutBack.setVisibility(View.GONE);
        mTextViewTitle.setText("设置");
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        this.setToogelButton();
    }

    /**
     * 设置语音播放
     */
    private void setToogelButton() {
        if ("true".equals(PreferenceUtil.getParam(Preferences.VOICE, "true"))) {
            mToggleButton.setToggleOn();
        } else {
            mToggleButton.setToggleOff();
        }
        mToggleButton.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean on) {
                if (!on) {
                    PreferenceUtil.setParam(Preferences.VOICE, "false");
                } else {
                    PreferenceUtil.setParam(Preferences.VOICE, "true");
                }
            }
        });
    }

    /**
     * 检测是否有蓝牙
     *
     * @return
     */
    private boolean checkBlueTooth() {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            showToast("本机没有找到蓝牙硬件或驱动");
            return false;
        }
        return true;
    }

    @Override
    protected void onSetListener() {
        mLayoutBluePrint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkBlueTooth()) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), BlueToothStateActivity.class);
                    intent.putExtra("bluetooth", true);
                    startActivity(intent);
                }
            }
        });

        mLayoutCheckVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkVersonUpdate();
            }
        });
        mLayoutOuttime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //超时设置
                startActivity(new Intent(getActivity(), OutTimeSetActivity.class));
            }
        });

        mLayoutExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showExitDialog();
            }
        });

    }

    private TipDialog mDialogExit;

    private void showExitDialog() {
        if (mDialogExit == null) {
            mDialogExit = new TipDialog(getActivity());
        }
        mDialogExit.setContent("确认退出登录?");
        mDialogExit.setCancelable(true);
        mDialogExit.setListener(new TipDialog.Listener() {
            @Override
            public void onDismiss() {
                mDialogExit.cancel();
            }

            @Override
            public void onConfirm() {
                mDialogExit.dismiss();
                unbindGetui();
            }
        });
        mDialogExit.show();
    }

    /**
     * 解绑个推
     */
    private void unbindGetui() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.UNBIND);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                exitApp();
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                exitApp();
            }
        });
    }

    private void exitApp() {
        Intent intent = new Intent(getActivity(), LoginModeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        App.getApp().cancelAccount();//注销
        startActivity(intent);
    }

    private String mApkUrl;//下载地址
    private String mUpdateVersion;//当前版本

    /**
     * 检查版本更新
     */
    public void checkVersonUpdate() {
        final String mCurrentVersion = CommonUtil.getVersionName(App.getApp());
        HttpUtils.RequestParam params = new HttpUtils.RequestParam();
        params.add("method", ApiName.APP_VERSION);
        params.add("clienttype", "ANDROID");
        params.add("sign", params.getMd5String());
        HttpUtils.getInstance().params(params).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                if (CommonUtil.isForeground(getActivity())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        try {
                            mApkUrl = new JSONObject(string).getJSONObject("data")
                                    .optString("native_android_download");
                            mUpdateVersion = new JSONObject(string).getJSONObject("data")
                                    .optString("native_android_version");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //是否更新
                        if (!mCurrentVersion.equals(mUpdateVersion)) {
                            File dir = new File(DIR.TEMP_APK);
                            //删除已存在的apk
                            if (dir.exists()) {
                                File[] files = dir.listFiles();
                                for (File file : files) {
                                    if (file.getName().contains(".apk")) {
                                        try {
                                            CommonUtil.deleteFile(file);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                            foundUpdate();
                        } else {
                            showToast("当前是最新版本");
                        }
                    } else {
                        showToast(responseResult.getInfo());
                    }
                }
            }
        });
    }

    private void foundUpdate() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showUpdateTip();
            }
        });
    }

    //下载应用
    private void downLoadApk() {
        HttpUtils.getInstance().loadFile(mApkUrl, new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
            }

            @Override
            public void onResponseProgress(long progress, long total, boolean done) {
                float per = (float) progress / (float) total * (float) 100;
                String pers = String.valueOf(per);
                if (pers.length() > 5) {
                    pers = pers.substring(0, 5);
                }
                final String finalPers = pers;
                ((BaseActivity) getActivity()).showDownProgress("正在下载" + " " + finalPers + "%");
            }

            @Override
            public void onHttpSuccess(byte[] bytes) {
                ((BaseActivity) getActivity()).showDownProgress("准备安装，请稍后");
                String savepath = DIR.TEMP_APK + "/" + mUpdateVersion + ".apk";
                File file = new File(savepath);
                try {
                    CommonUtil.byte2File(bytes, file.getParent(), file.getName());
                    ((BaseActivity) getActivity()).dismissDownProgress();
                    SysUtil.installApk(App.getApp(), file.getPath());
                } catch (Exception e) {
                    LogDebug.e(e);
                }
            }
        });
    }

    private TipDialog mUpdateTip;

    private void showUpdateTip() {
        if (mUpdateTip == null) {
            mUpdateTip = new TipDialog(getActivity());
            mUpdateTip.setContent("发现新版，是否更新？");
            mUpdateTip.setCancle("否");
            mUpdateTip.setConfirm("是");
            mUpdateTip.setCancelable(true);
            mUpdateTip.setListener(new TipDialog.Listener() {
                @Override
                public void onConfirm() {
                    downLoadApk();
                }

                @Override
                public void onDismiss() {
                    super.onDismiss();
                    mUpdateTip.dismiss();
                }

            });
        }
        mUpdateTip.show();
    }
}
